﻿using DbUp;
using System;
using System.Linq;
using System.Reflection;

namespace LightPublisherCms.Data.DbUpgrade
{
    class Program
    {
        static int Main(string[] args)
        {
            string defaultConnectionString =
                "Server=(local)\\SqlExpress; Database=LightPublisherCms; Trusted_connection=true";

            Console.WriteLine("LightPublisherCms.Data.DbUpgrade");
            Console.WriteLine("The data base generation tool for the LightPublisherCms.");
            Console.WriteLine("Usage:");
            Console.WriteLine("DbUpgrade.exe CONNECTION_STRING");
            Console.WriteLine("Example: DbUpgrade.exe {0}", defaultConnectionString);
            Console.WriteLine("Default connection string: {0}", defaultConnectionString);

            string connectionString = args.FirstOrDefault() ?? defaultConnectionString;

            Console.WriteLine();
            Console.WriteLine("Use connection string: '{0}' y/n?", connectionString);
            string r = Console.ReadLine();
            if (r.Length <= 0 || r.ToUpper()[0] != 'Y')
            {
                return 0;
            }

            var upgrader =
                DeployChanges.To
                    .SqlDatabase(connectionString)
                    .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                    .LogToConsole()
                    .Build();

            var result = upgrader.PerformUpgrade();

            if (!result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
                return -1;
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Success!");
            Console.ResetColor();
            return 0;
        }
    }
}
